package com.dream.inspect.modules.business.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.dream.inspect.common.utils.DateFormatUtil;
import com.dream.inspect.common.utils.DatetimeUtil;
import com.dream.inspect.common.utils.PageUtils;
import com.dream.inspect.common.utils.Query;
import com.dream.inspect.modules.business.dao.InstructionsDao;
import com.dream.inspect.modules.business.dao.InstructionsTargetDao;
import com.dream.inspect.modules.business.entity.InstructionsEntity;
import com.dream.inspect.modules.business.entity.InstructionsTargetEntity;
import com.dream.inspect.modules.business.service.InstructionsService;
import com.dream.inspect.modules.dream.dao.InstructionsMapper;
import com.dream.inspect.modules.dream.dao.InstructionsTargetMapper;
import com.dream.inspect.modules.dream.pojo.InstrucationsFormMap;
import com.dream.inspect.modules.sys.dao.SysUserDao;
import com.dream.inspect.modules.sys.entity.SysUserEntity;


@Service("instructionsService")
public class InstructionsServiceImpl extends ServiceImpl<InstructionsDao, InstructionsEntity> implements InstructionsService {

	@Resource
	private InstructionsDao instructionsDao;
	@Resource
	private InstructionsTargetDao instructionsTargetDao;
	@Resource
	private InstructionsMapper instructionsMapper;
	@Resource
	private InstructionsTargetMapper instructionsTargetMapper;
	@Resource
	private SysUserDao sysUserDao;
	
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
    	String level = (String)params.get("level");
        Page<InstructionsEntity> page = this.selectPage(
                new Query<InstructionsEntity>(params).getPage(),
                new EntityWrapper<InstructionsEntity>()
                .eq("delete_flag", "0")
                .eq(StringUtils.isNotBlank(level),"level", level)
        );

        return new PageUtils(page);
    }


	@Override
	public PageUtils findInstructionList(Map<String, Object> params) {
		Page<InstrucationsFormMap> page = selectThisPage(new Query<InstrucationsFormMap>(params),
                new Query<InstrucationsFormMap>(params).getPage()
        );

        return new PageUtils(page);
	}
	
	private Page<InstrucationsFormMap> selectThisPage(Map<String ,Object> map, Page<InstrucationsFormMap> page) {
        page.setRecords(instructionsDao.findInstructionList(map,page));
        return page;
    }


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void insertEntity(Map<String, Object> params) throws Exception {
		Date now = new Date();
		InstrucationsFormMap instructions = insertParamToFormMap(params);
		instructions.put("createTime", DatetimeUtil.getDate());
		instructionsDao.insertInstructions(instructions);
		//instructionsMapper.addEntity(instructions);
		List<JSONObject> depts = JSONArray.parseArray(params.get("dept") + "" ,JSONObject.class);
		//List<InstrucationsTargetFormMap> targets = new ArrayList<InstrucationsTargetFormMap>();
		//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		/*for(String deptId : deptIds){
			InstrucationsTargetFormMap target = new InstrucationsTargetFormMap();
			target.put("instructionsId", instructions.get("id"));
			target.put("jszldw", deptId);
			target.put("jssj", sdf.format(now));
			target.put("jszt", "0");
			target.put("createUser", params.get("createUser"));
			target.put("createTime", sdf.format(now));
			targets.add(target);
		}
		instructionsTargetMapper.batchSave(targets);*/
		for(JSONObject dept : depts){
			InstructionsTargetEntity target = new InstructionsTargetEntity();
			target.setCreateTime(now);
			target.setCreateUser(Long.parseLong(params.get("createUser").toString()));
			target.setDeleteFlag("0");
			target.setInstructionsId(Long.parseLong(instructions.get("id").toString()));
			target.setJssj(now);
			target.setJszt("0");
			target.setReadFlag("0");
			target.setJszldw(Long.parseLong(dept.get("deptId") + ""));
			if(dept.containsKey("userId")&&!"".equals(dept.get("userId").toString())){
				target.setJsyh(Long.parseLong(dept.get("userId") + ""));
				instructionsTargetDao.insert(target);
			}else{
				// 插入该部门下所有的人
				List<SysUserEntity> userlist = sysUserDao.selectList(new EntityWrapper<SysUserEntity>().eq("DEL_FLAG", "0").eq("DEPT_ID", Long.parseLong(dept.get("deptId") + "")).eq("USER_FLAG","1"));
				for (SysUserEntity user : userlist) {
					target.setJsyh(user.getUserId());
					instructionsTargetDao.insert(target);
				}
			}
		}
	}
	
	@Override
	public int selectThisMonthCount(Map<String, String> params) {
//		String userDwId = params.get("userDwId");
//		String userId = params.get("userId");
		String thisMonthFlg = params.get("thisMonthFlg");//本月标志
		if (StringUtils.isNotEmpty(thisMonthFlg)) {
			if ("1".equals(thisMonthFlg)) {
				String dt = DateFormatUtil.getFirstDayOfMonthForString();
				params.put("thisMonth", dt);
			}
		}
		//查询条件
        //EntityWrapper<InstructionsEntity> wrapper = new EntityWrapper<InstructionsEntity>();//addCondition(params);
        /*if (StringUtils.isNotEmpty(thisMonthFlg)) {
			if ("1".equals(thisMonthFlg)) {
				String dt = DateFormatUtil.getFirstDayOfMonthForString();
				wrapper.and(" Date(i.CREATE_TIME) >= '" + dt + "'");
			}
		}
        //用户部门名称
        if (StringUtils.isNotEmpty(userDwId)) {
            wrapper.andNew();
            wrapper.eq("it.JSZLDW", userDwId);
            wrapper.or("i.FBDW_ID={0}", userDwId);
        }
        int countNum = baseMapper.selectThisMonthCount(wrapper);*/
        int countNum = baseMapper.selectMonthCount(params);
        return countNum;
	}

	private InstrucationsFormMap insertParamToFormMap(Map<String, Object> params){
		InstrucationsFormMap instructions = new InstrucationsFormMap();
		instructions.put("titleName", params.get("titleName"));
		instructions.put("fbdwId", params.get("fbdwId"));
		instructions.put("hysj", params.get("hysj"));
		instructions.put("zlxq", params.get("zlxq"));
		instructions.put("createUser", params.get("createUser"));
		instructions.put("zlzt", "0");//params.get("zlzt"));
		instructions.put("level", params.get("level"));
		instructions.put("msgFlag", params.get("msgFlag"));
		return instructions;
	}


	@Override
	public PageUtils webQueryPage(Map<String, Object> params) {
		Page<InstrucationsFormMap> page = new Query<InstrucationsFormMap>(params).getPage();
		page.setRecords(instructionsDao.findList(params,page));
        return new PageUtils(page);
	}

	@Override
	public List<InstructionsEntity> findInstructionsForSearchPage(Map<String, String> params) {
		int currPage = Integer.valueOf(params.get("currPage"));
        int pageSize  = Integer.valueOf(params.get("pageSize"));
        currPage = (currPage - 1) * pageSize;
        List<InstructionsEntity> sqrList = new ArrayList<InstructionsEntity>();
        //组装条件
        EntityWrapper<InstructionsEntity> wrapper = addCondition(params);
        sqrList = baseMapper.findInstructionsForSearchPage(wrapper, currPage, pageSize);
        return sqrList;
	}


	@Override
	public int findInstructionsForSearchPageCount(Map<String, String> params) {
		//查询条件
        EntityWrapper<InstructionsEntity> wrapper = addCondition(params);

        int countNum = baseMapper.findInstructionsForSearchPageCount(wrapper);
        return countNum;
	}
	
	/**
	 * 拼接查询条件
	 * 
	 * @param params
	 * @return
	 */
	private EntityWrapper<InstructionsEntity> addCondition(Map<String, String> params) {
		String searchText = params.get("searchText");
		
		EntityWrapper<InstructionsEntity> wrapper = new EntityWrapper<InstructionsEntity>();
		wrapper.setEntity(new InstructionsEntity());
		//全文检索条件
		if (StringUtils.isNotEmpty(searchText)) {
			wrapper.andNew();
    		wrapper.like("sd.name", searchText);
    		wrapper.or("t.TITLE_NAME like {0}", "%" + searchText + "%");
		}
    
    	return wrapper;
	}
}
